﻿using System;

namespace xlstool
{
    using NPOI.HSSF.UserModel;
    using NPOI.HSSF.Util;
    using NPOI.SS.UserModel;
    using System.Drawing;

    public class Excel2003Sheet
    {
        internal ISheet sheet { get; set; }
        internal Excel2003Workbook workbook { get; set; }
        internal Excel2003Sheet(ISheet sheet, Excel2003Workbook workbook)
        {
            this.sheet = sheet;
            this.workbook = workbook;
        }
        public string Name { get { return sheet.SheetName; } }
        public int SheetNo { get { return workbook.read_sheetno(Name); } }
        public bool Hidden { get { return workbook.wb.IsSheetHidden(SheetNo); } }
        public bool IsActive { get { return this.workbook.wb.ActiveSheetIndex == SheetNo; } }

        public void ChangeSheetName(string name)
        {
            workbook.wb.SetSheetName(SheetNo, name);
        }
        public void SetHidden(bool hidden)
        {
            workbook.wb.SetSheetHidden(SheetNo, hidden);
        }
        public void Active()
        {
            
            this.workbook.wb.SetActiveSheet(SheetNo);
        }
        public Excel2003Row ToRow(int index)
        {
            index--;
            if (index < 0) throw new ArgumentException();

            var row = sheet.GetRow(index);
            if (row == null) row = sheet.CreateRow(index);
            return new Excel2003Row(row, this);
        }

        public IEnumerable<Excel2003Row> LoopRow()
        {
            int firstRowIndex = sheet.FirstRowNum;
            int lastRowIndex = sheet.LastRowNum;
            for (int rowNum = firstRowIndex; rowNum <= lastRowIndex; rowNum++)
            {
                IRow row = sheet.GetRow(rowNum);
                if (row == null) continue;
                yield return new Excel2003Row(row, this);
            }
        }
        public void SetColumnHidden(int columnIndex, bool hidden = true)
        {
            columnIndex--;
            if (columnIndex < 0) return;
            sheet.SetColumnHidden(columnIndex, hidden);
        }
        public bool IsColumnHidden(int columnIndex)
        {
            columnIndex--;
            if (columnIndex < 0) return false;
            return sheet.IsColumnHidden(columnIndex);
        }
        public void SetColumnHidden(string columnIndex, bool hidden = true)
        {
            SetColumnHidden(Excel2003Cell.to_cellno(columnIndex), hidden);
        }
        public bool IsColumnHidden(string columnIndex)
        {
            return IsColumnHidden(Excel2003Cell.to_cellno(columnIndex));
        }
        public void SetColumnWidth(int columnIndex, int width)
        {
            columnIndex--;
            if (columnIndex < 0) return;
            sheet.SetColumnWidth(columnIndex, width);
        }
        public void SetColumnWidth(string columnIndex, int width)
        {
            SetColumnWidth(Excel2003Cell.to_cellno(columnIndex), width);
        }
    }
}
